package kr.hkit.powerjava.chapter24.submit2.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.hkit.powerjava.chapter24.submit2.vo.Student;

public class StudentDao implements InterfaceDao<Student> {

	private ArrayList<Student> lists;
	private final String filePath = "studentList.data";
	
	
	@Override
	public void insertItem(Student item) {
		if (!lists.contains(item)) { //false면 넣어주기
			lists.add(item);
		}
	}

	@Override
	public void deleteItem(Student item) {
		if (lists.contains(item)) {
			lists.remove(item);
		}
	}

	@Override
	public void updateItem(Student item) {
		if(lists.contains(item)) {
			lists.set(lists.indexOf(item), item);
		}
	}

	@Override
	public Student searchItem(Student item) {
		Student searchValue = null;
		if (lists.contains(item))
			searchValue = lists.get(lists.indexOf(item));
		return searchValue;
	}

	@Override
	public void prnItemList(Comparator<Student> comp) {
		if (comp == null) { //null이면 그냥 기본
			Collections.sort(lists);
		}else{
			Collections.sort(lists, comp);
		}
		for (Student std : lists) {
			System.out.println(std);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void loadFile() {
		ObjectInputStream ois= null;
	
		try {
			ois = new ObjectInputStream (new BufferedInputStream(new FileInputStream(filePath)));
			lists = (ArrayList<Student>) ois.readObject();
		} catch (FileNotFoundException e) { //없을경우
			try {
				new File(filePath).createNewFile();
				lists = new ArrayList<>(); 
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) try {ois.close();}catch(Exception e) {}
		}
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream (new BufferedOutputStream(new FileOutputStream(filePath)));
			oos.writeObject(lists);
		} catch (Exception e) {
		} finally {
			if (oos != null) try {oos.close();}catch(Exception e) {}
		}
	}
}
